

import dayjs from "dayjs"
import { cache } from '@/utils'
import _ from 'lodash'
export const authMap = new Map()
authMap.set("带回", { label: "申请学徒带回", key: 1, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("维修", { label: "新建维修", key: 2, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("返修", { label: "提交返修", key: 3, visible: true, icon: "/static/image/more/fanxiu.png" })
authMap.set("送回", { label: "客户不修送回", key: 4, visible: true, icon: "/static/image/more/songhui.png" })
authMap.set("送机", { label: "申请学徒送机", key: 5, visible: true, icon: "/static/image/more/songji.png" })
authMap.set("postApplyOvertime", { label: "申请加班", key: 6, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("postApplyRefund", { label: "申请退款", key: 7, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("postApplyTransfer", { label: "转单", key: 8, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("postApplyUpdate", { label: "申请修改", key: 9, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("postBringBack", { label: "本人带回", key: 10, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("postComplete", { label: "完成", key: 11, visible: false, icon: "/static/image/more/daihui.png" })
authMap.set("postGgimg", { label: "广告图", key: 12, visible: false, icon: "/static/image/more/daihui.png" })
authMap.set("postInvoiceEdit", { label: "发票信息", key: 13, visible: true, icon: "/static/image/more/fapiao.png" })
authMap.set("postOrderbranchMoney", { label: "设置送返修现金", key: 14, visible: false, icon: "/static/image/more/daihui.png" })
authMap.set("postReception", { label: "接单", key: 15, visible: false, icon: "/static/image/more/daihui.png" })
authMap.set("postSubmitDetails", { label: "修改详情", key: 16, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("postWorkerRemarks", { label: "师傅备注", key: 17, visible: true, icon: "/static/image/more/daihui.png" })
authMap.set("postPayment", { label: "添加支付", key: 18, visible: true, icon: "/static/image/more/payment.png" })
authMap.set("postDewancheng", { label: "转待完成", key: 19, visible: false, icon: "/static/image/more/payment.png" })
authMap.set("postPraise", { label: "上传好评", key: 20, visible: false, icon: "/static/image/more/payment.png" })
authMap.set("postQuote", { label: "修改报价", key: 21, visible: true, icon: "/static/image/more/payment.png" })
authMap.set("postRepairSubmitDetails", { label: "返修详情提交", key: 22, visible: true, icon: "/static/image/more/payment.png" })
authMap.set("postOrderPraiseSelect", { label: "多好评提交", key: 23, visible: true, icon: "/static/image/more/payment.png" })
authMap.set("postBringBack", { label: "本人带回", key: 24, visible: true, icon: "/static/image/more/daihui.png"})
authMap.set("postGG", { label: "提交广告图", key: 25, visible: true, icon: "/static/image/more/daihui.png"})
authMap.set("postMtBindCode", { label: "绑定券码", key: 26, visible: true, icon: "/static/image/more/daihui.png"})
authMap.set("postMtServiceCompleted", { label: "服务完成", key: 27, visible: true, icon: "/static/image/more/daihui.png"})

// 对象转查询字符串
export const queryString = (params) => {
	if(!(params instanceof Object)) return "";
	return Object.entries(params).reduce((str, [key, value]) => `${str}${key}=${value}&`, "?").slice(0, -1)
}

// 跳转下一页
export const nav = (url) => {
	uni.navigateTo({ url })
}

// 关闭当前页跳转到指定页
export const rep = (url) => {
	uni.redirectTo({ url })
}

export const swi = (url) => {
	uni.switchTab({ url })
}

// 返回
export const back = (delta = 1) => {
	uni.navigateBack({
		delta
	})
}

export const makePhoneCall = (phoneNumber) => {
	uni.makePhoneCall({ phoneNumber })
}


export const toast = (title, icon = "none", mask = true) => {
	uni.showToast({
		title, 
		icon, 
		mask
	})
}

// 获取几天后的日期
export const getDateAfter = (diff = 3) => {
	let array = [];
	for(let i =0; i < diff; i++){
		let cur = dayjs().add(i, 'day').format("YYYY-MM-DD")
		array.push(cur)
	}
	return array
}

// 截取时间
export const getHalfHours = (isNowDay) => {

	let timeLineArr = []
	let halfHour = 30 * 60 * 1000
	let nowTimeStamp = new Date().getTime()
	let startTimeStamp = new Date().setHours(9, 0, 0, 0)
	let endTimestamp = new Date().setHours(24, 30, 0, 0)
	let timeIndex = 0
	startTimeStamp -= halfHour
	for (let i = startTimeStamp; i < endTimestamp; i += halfHour) {
		timeLineArr.push({
			id: timeIndex,
			timeLine: getTimeLine(i, i + halfHour),
			isShow: isNowDay ? (i + halfHour > nowTimeStamp ? true : false) : true,
		})
		timeIndex++
	}

	return timeLineArr

	}

export const getTimeLine = (start, end) => {
	let timeStart =
		(new Date(start).getHours() >= 10 ? new Date(start).getHours() : '0' + new Date(start).getHours()) +
		':' +
		(new Date(start).getMinutes() >= 10 ? new Date(start).getMinutes() : '0' + new Date(start).getMinutes())
	let timeEnd =
		(new Date(end).getHours() >= 10 ? new Date(end).getHours() : '0' + new Date(end).getHours()) +
		':' +
		(new Date(end).getMinutes() >= 10 ? new Date(end).getMinutes() : '0' + new Date(end).getMinutes())
	return [timeStart, timeEnd]
}


// 判断对象
export const isObject = (o) => Object.prototype.toString.call(o) === '[object Object]'
// 格式化组件自定义样式
export const formatStyle = (o) => {
  if(!isObject(o)) return { style: "" };
  return Object.entries(o).reduce((acc, [key, value]) => {
    if(isObject(o[key])) {
      if(!acc[key]) acc[key] = '';
      acc[key] = Object.entries(o[key]).reduce((style, [k, v]) => style += `${k}:${v};`, "")
    }else{
      if(!acc["style"]) acc["style"] = ""
      acc["style"] += `${key}:${value};`
    }
    return acc
  }, {})
}


/**
 * 打散权限
 * @param{mode} all - 所有有权限的列表 more 更多操作的选项
 */
export const scatterAuth = (data, mode = "all") => {
	if(!data) return;
	try{
		const authList = [];
		const baseMap = {
			key: 0, 
			visible: true, 
			icon: "/static/image/more/payment.png"
		}
		Object.entries(data).map(([key, value]) => {
			if(typeof data[key] !== 'object'){
				if(value === 1){
					if(!authMap.get(key)){
						baseMap.label = key
						authList.push(baseMap)
						return
					}
					authList.push(authMap.get(key))
				}
			}else{
				Object.entries(data[key]).map(([k, v]) => {
					if(v === 1){
						if(!authMap.get(k)){
							baseMap.label = k
							authList.push(baseMap)
							return
						}
						authList.push(authMap.get(k))
					}
				})
			}
			
		})
		return authList;
		
	}catch(e){
		console.log(e,'权限解析错误')
		return []
	}
}

export const transTree = (data) => {
    let result = []
    let map = {}
    if (!Array.isArray(data)) {//验证data是不是数组类型
        return []
    }
    data.forEach(item => {//建立每个数组元素id和该对象的关系
        map[item.id] = item //这里可以理解为浅拷贝，共享引用
    })
    data.forEach(item => {
        let parent = map[item.pid] //找到data中每一项item的爸爸
        if (parent) {//说明元素有爸爸，把元素放在爸爸的children下面
            (parent.children || (parent.children = [])).push(item)
        } else {//说明元素没有爸爸，是根节点，把节点push到最终结果中
            result.push(item) //item是对象的引用
        }
    })
    return result //数组里的对象和data是共享的
}

export const copyText = (text) => {
	uni.setClipboardData({
		data: text,
		success: r => {
			console.log(r,'---')
		}
	})
}
// 查找搜索key
export const matchSearchKey = (list) => {
	if(!list || !Array.isArray(list)) return;
	return list.reduce((acc, item) => {
		acc[item.name] = item.value || ""
		return acc
	}, {})
}

export const dateTimeKV = (fieldList) => {
	if(!Array.isArray(fieldList)) {
		console.error("参数错误")
		return
	}
	const result = fieldList.reduce((acc, item) => {
		const whiteList = ["date", "year-month", "datetime"]
		if(item.mode && whiteList.includes(item.mode)){
			acc[item.name] = item.mode
		}
		return acc
	}, {})
	return result
}

// 获取缓存列表数据
export const getCacheList = (cacheKey, status) => {
	const nowTime = Date.now()
	const data = cache.get[cacheKey]() || {}
	if(!data[status]) return {}
	if(nowTime > data[status].expireTime){
		delete data[status]
		return {}
	}
	return data[status]
}
// 防抖
export const debounceUtil = _.debounce((fn, wait = 1000) => fn(), 500, {
  leading: false,
  trailing: true
})